const db = require('../config/db.config');

class Dify {
    // 创建新会话
    static async createSession(userId, sessionName) {
        const [result] = await db.execute(
            'INSERT INTO dify_sessions (user_id, session_name) VALUES (?, ?)',
            [userId, sessionName]
        );
        return result.insertId;
    }

    // 获取会话详情
    static async getSessionById(sessionId, userId) {
        const [rows] = await db.execute(
            'SELECT * FROM dify_sessions WHERE session_id = ? AND user_id = ? AND is_deleted = 0',
            [sessionId, userId]
        );
        return rows[0];
    }

    // 保存消息
    static async saveMessage(sessionId, userId, role, content, messageIdDify = null, metadata = null, conversationId = null, imageUrl = null) {
        const [result] = await db.execute(
            'INSERT INTO dify_messages (session_id, user_id, role, content, message_id_dify, metadata, conversation_id_dify, image_url) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
            [sessionId, userId, role, content, messageIdDify, metadata ? JSON.stringify(metadata) : null, conversationId, imageUrl]
        );
        return result.insertId;
    }

    // 获取会话的消息历史
    static async getMessages(sessionId, userId) {
        const [rows] = await db.execute(
            'SELECT * FROM dify_messages WHERE session_id = ? AND user_id = ? ORDER BY created_at DESC',
            [sessionId, userId]
        );
        return rows.map(row => ({
            ...row,
            conversation_id: row.conversation_id_dify || null,  // 使用 Dify 的 conversation_id
            user_id: row.user_id
        }));
    }

    // 更新会话的 conversation_id
    static async updateConversationId(sessionId, conversationId) {
        const [result] = await db.execute(
            'UPDATE dify_sessions SET conversation_id_dify = ? WHERE session_id = ?',
            [conversationId, sessionId]
        );
        return result.affectedRows > 0;
    }

    // 删除会话
    static async deleteSession(sessionId, userId) {
        try {
            // 使用软删除，将 is_deleted 设置为 1
            const [result] = await db.execute(
                'UPDATE dify_sessions SET is_deleted = 1 WHERE session_id = ? AND user_id = ?',
                [sessionId, userId]
            );
            
            if (result.affectedRows === 0) {
                throw new Error('会话不存在或已被删除');
            }
            
            return true;
        } catch (error) {
            console.error('删除会话错误:', error);
            throw error;
        }
    }

    // 重命名会话
    static async renameSession(sessionId, userId, newName) {
        try {
            const [result] = await db.execute(
                'UPDATE dify_sessions SET session_name = ? WHERE session_id = ? AND user_id = ? AND is_deleted = 0',
                [newName, sessionId, userId]
            );
            
            if (result.affectedRows === 0) {
                throw new Error('会话不存在或已被删除');
            }
            
            return true;
        } catch (error) {
            console.error('重命名会话错误:', error);
            throw error;
        }
    }

    // 获取所有会话
    static async getSessions(userId) {
        try {
            const [rows] = await db.execute(
                'SELECT * FROM dify_sessions WHERE user_id = ? AND is_deleted = 0 ORDER BY updated_at DESC',
                [userId]
            );
            return rows;
        } catch (error) {
            console.error('获取会话列表错误:', error);
            throw error;
        }
    }
}

module.exports = Dify; 